package com.cke.yang.common.infra.utils;

import com.cke.yang.common.domain.model.SecUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户上下文工具类
 *
 * @author yuyang
 * @date 2025-11-22 00:00:00
 */
public class UserDetailsUtils {
    
    /**
     * 获取当前上下文的用户详情
     * @return UserDetails 对象，如果未认证则返回 null
     */
    public static SecUserDetails getCurrentUserDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            return (SecUserDetails) authentication.getPrincipal();
        }
        return null;
    }

    public static Long getCurrentUserId() {
        SecUserDetails details = getCurrentUserDetails();
        if (details == null) {
            return null;
        }
        return details.getUserId();
    }

    public static Long getCurrentRoleId() {
        SecUserDetails details = getCurrentUserDetails();
        if (details == null) {
            return null;
        }
        return details.getCurrentRoleId();
    }
}
